class MakeNewPost {
  
  Blog _blog;
  MakeNewPost(Blog blog){
    _blog = blog;
  }
 
  void showWindow(){
	// set "NEW POST" active on side bar
  	SideBar bar = _blog.getSideBar();
    bar.setActive(document.query('#MakePost'));
	
  	document.query('#PostWindow').innerHTML = Windows.makeNewPost;
  	document.query('#cancelPost').on.click.add((events) => closeWindow());
    document.query('#addPost').on.click.add((events) => postToWall());
  }
  
  void postToWall(){ 
	var title = document.query('#titleTxt');
	var content = document.query('#contentTxt');
	var tags = document.query('#tags');
	
	if(!isValidTagName(tags.value)){
		showErrorTag(tags.value);
		return;
	}
    
    if(title.value == "" && content.value == ""){
      window.alert('Please write a post');
    }else{  
      Map newPost = new Map();
      String user = _blog.getCurrentUser();
	  
  	  if(user == null || user == ""){
  	    window.alert("in postToWall: user == null || user.equals('')");
  	  }
      newPost['id'] = null;
      newPost['pubDate'] = null;
      newPost['user'] = user;
      newPost['title'] = title.value;
      newPost['content'] = content.value;
      newPost['tags'] = tags.value;
      
      _blog.addPostToServer(newPost);
	  document.query('#PostWindow').innerHTML = '';
	  SideBar bar = _blog.getSideBar();
	  bar.setActive(document.query('#allposts'));
	  document.query('#pagename').innerHTML = 'All Posts';
    }
  }
	// 
	bool isValidTagName(name) {
		if(name == null)
			return false;
		RegExp tagsexp = const RegExp(@"(^[A-Za-z\s]*$)");
		return tagsexp.hasMatch(name);
	}
	
	void showErrorTag(String tagss){
	  List tags = tagss.split(" ");
		for(num i = 0; i < tags.length; i++){
			if(!isValidTagName(tags[i])){
				String t = tags[i];
				document.query('#errortags').innerHTML = 'Invalid tag name: $t.<br/>Tag name contains letters only';
				break;	
			}
		}
	}

  
  void closeWindow(){
	document.query('#PostWindow').innerHTML = '';
	SideBar bar = _blog.getSideBar();
    bar.revert();
  }
}
